package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.DimJoinFunction;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.DimUtil;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.RedisUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.hadoop.hbase.client.Connection;
import redis.clients.jedis.Jedis;

/**
 * @author Felix
 * @date 2023/8/11
 * 同步维度关联的实现类
 * 模板方法设计模式
 *      在父类中定义完成某一个功能的核心算法的骨架(步骤)，但是某些步骤在父类中实现不了，需要延迟到子类中去实现
 *      好处：父类中定义步骤，子类在不改变核心算法骨架的前提下，每一个子类都可以有自己不同的实现
 */
public abstract class DimMapFunction<T> extends RichMapFunction<T,T> implements DimJoinFunction<T> {
    private String tableName;
    private Connection hbaseConn;
    private Jedis jedis;

    public DimMapFunction(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        hbaseConn = HbaseUtil.getHbaseConnection();
        jedis = RedisUtil.getRedisClient();
    }

    @Override
    public void close() throws Exception {
        HbaseUtil.closeHbaseConnection(hbaseConn);
        RedisUtil.closeRedisClient(jedis);
    }
    @Override
    public T map(T obj) throws Exception {
        //根据流中的对象获取要关联的维度的主键
        String key = getKey(obj);
        //根据维度的主键获取维度对象
        JSONObject dimInfoJsonObj = DimUtil.getDimInfo(jedis, hbaseConn, GmallConfig.HBASE_NAMESPACE, tableName, key);
        //将维度对象相关的维度属性补充到流中对象上
        join(obj,dimInfoJsonObj);
        return obj;
    }


}
